package com.qinggeng.project.tool.pay.utils;

import com.github.wxpay.sdk.WXPayUtil;
import com.qinggeng.common.exception.CustomException;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 支付工具
 */
public class PayUtils {

    /**
     * 生成订单号
     * @return String
     */
    public static String getOrderCode() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int a = (int)(Math.random() * 9000.0D) + 1000;
        System.out.println(a);
        Date date = new Date();
        String str = sdf.format(date);
        String[] split = str.split("-");
        String s = split[0] + split[1] + split[2];
        String[] split1 = s.split(" ");
        String s1 = split1[0] + split1[1];
        String[] split2 = s1.split(":");
        return split2[0] + split2[1] + split2[2] + a;
    }


    /**
     * 转换request 为Map
     * @param request
     * @return
     */
    public static Map<String,String> parseRequest(HttpServletRequest request){
      InputStream inStream = null;
      ByteArrayOutputStream outSteam = null;
      try {
          inStream = request.getInputStream();
          outSteam = new ByteArrayOutputStream();
          byte[] buffer = new byte[1024];
          int len = 0;
          while ((len = inStream.read(buffer)) != -1) {
              outSteam.write(buffer, 0, len);
          }
          String resultXml = new String(outSteam.toByteArray(), "utf-8");
          return WXPayUtil.xmlToMap(resultXml);
      }catch (Exception e){
            throw new CustomException("解析异常");
      }finally {
          try {
              inStream.close();
              outSteam.close();
          }catch (Exception e){
              throw new CustomException("解析异常");
          }
      }
    }


}
